package com.neusoft.bizcore.auth.service.impl;

import java.util.List;

import javax.persistence.EntityNotFoundException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.neusoft.bizcore.auth.converter.AuthPermissionConverter;
import com.neusoft.bizcore.auth.dto.AuthPermissionDTO;
import com.neusoft.bizcore.auth.model.AuthPermission;
import com.neusoft.bizcore.auth.repository.AuthPermissionRepository;
import com.neusoft.bizcore.auth.service.AuthPermissionService;
import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.bizcore.web.support.Searchable;

@Service
public class AuthPermissionServiceImpl implements AuthPermissionService {

    @Autowired
    private AuthPermissionRepository authPermissionRepository;
    @Autowired
    private AuthPermissionConverter authPermissionConverter;

    @Override
    public List<AuthPermissionDTO> findAll() {
        final List<AuthPermission> models = this.authPermissionRepository.findAll();
        final List<AuthPermissionDTO> dtos = this.authPermissionConverter.toListDTO(models);
        return dtos;
    }

    @Override
    public Page<AuthPermissionDTO> search(final Pageable pageable, final Searchable searchable) {
        final Page<AuthPermission> models = this.authPermissionRepository.search(pageable, searchable);
        return this.authPermissionConverter.toPageDTO(models);
    }

    @Override
    public AuthPermissionDTO create(final AuthPermissionDTO dto) {
        final AuthPermission model = this.authPermissionConverter.toModel(dto);
        this.authPermissionRepository.save(model);
        return this.authPermissionConverter.toDTO(model);
    }

    @Override
    public AuthPermissionDTO update(final Long id, final AuthPermissionDTO dto) {
        AuthPermission model;
        try {
            model = this.authPermissionRepository.getOne(id);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, id);
        }

        dto.setId(model.getId());
        model = this.authPermissionConverter.toModel(dto);
        this.authPermissionRepository.save(model);

        return this.authPermissionConverter.toDTO(model);
    }

    @Override
    public AuthPermissionDTO details(final Long id) {
        AuthPermission model;
        try {
            model = this.authPermissionRepository.getOne(id);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, id);
        }

        return this.authPermissionConverter.toDTO(model);
    }

    @Override
    public void delete(final Long id) {
        this.authPermissionRepository.deleteById(id);
    }

}
